package parser;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class Parser {

	private String filePath;

	public Parser(String path) {
		filePath = path;
	}

	/**
	 * Creates a DOM structure object out of the given XML source file.
	 * 
	 * @return XML data in DOM structure.
	 * @throws ParseException
	 *             if the XML document builder couldn't be created, a parsing
	 *             error occours or the XML file source couldn't be opened.
	 */
	public Document parse() throws ParseException {
		// get DOM factory and configure it
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		// disable XML document validation
		domFactory.setValidating(false);

		// create document builder
		DocumentBuilder builder = null;
		try {
			builder = domFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			throw new ParseException("Couldn't create document builder.", e);
		}
		// create XML document in DOM structure
		Document document = null;
		try {
//	  		System.out.println(filePath);
//	  		File f = new File(filePath);
			document = builder.parse(new File(filePath));
//            Desktop.getDesktop().open(f);
		} catch (SAXException e) {
			throw new ParseException("Parsing Error", e);
		} catch (IOException e) {
			throw new ParseException("Couldn't open the file: " + filePath, e);
		}
		return document;
	}
}
